package com.jwdf.uda.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.event.FollowEvent;
import com.jwdf.uda.event.MessageNoticeEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.FollowListAction;
import com.jwdf.uda.http.action.UserAddFollowAction;
import com.jwdf.uda.http.action.UserCancelFollowAction;
import com.jwdf.uda.ui.adapter.UserSimpleAdapter;
import com.jwdf.uda.ui.adapter.item.UserSimpleItem;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.ui.fragment.base.SimpleListFragment;
import com.jwdf.uda.utils.AppBus;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.ToastUtils;

import retrofit2.Response;

/**
 * Created by Administrator on 2016/5/16.
 */
public class FollowActivity extends AbsTitleBarActivity {

    public static void start(Context context, String userId) {
        Intent intent = new Intent(context, FollowActivity.class);
        intent.putExtra("uid", userId);
        context.startActivity(intent);
    }

    @Override
    protected String getTopTitle() {
        String title = "关注的人";
        if (getIntent().hasExtra("uid")) {
            title = "Ta关注的人";
        }
        return title;
    }

    @Override
    protected BaseFragment onCreateContentFragment() {
        return new InnerListFragment();
    }

    @Override
    protected Bundle onPutArguments() {
        Bundle args = new Bundle();
        args.putString("uid", getIntent().getStringExtra("uid"));
        return args;
    }

    public static class InnerListFragment extends SimpleListFragment {
        private UserSimpleAdapter mAdapter;

        @Override
        protected void initViews() {
            String uid = getArguments().getString("uid", "");
            mAdapter = new UserSimpleAdapter(getActivity());
            mAdapter.setCurrentUser(TextUtils.isEmpty(uid));
            mAdapter.setOnUserFollowTypeListener(createUserFollowTypeListener());
            mDataBinding.commonFragmentList.setAdapter(mAdapter);
        }

        @Override
        protected void onListItemClick(int position) {
            PbBean.PbUserSimple user = mAdapter.getItem(position).userSimple;
            UserInfoActivity.start(getContext(), user.getUserId(), user.getIsDesigner());
        }
        @Override
        protected void requestData(final boolean refresh) {
            if(refresh && mAdapter.isEmpty()) {
                showProgressDialog();
            }
            int offset = refresh ? 0 : mAdapter.getCount();
            onNewRequestCall(FollowListAction.newInstance(getContext(), offset, getArguments().getString("uid", ""))
                                     .request(new AHttpService.IResCallback<PbBean.PbResUserGetFollowList>() {
                                         @Override
                                         public void onCallback(int resultCode, Response<PbBean.PbResUserGetFollowList> response, PbBean.PbBaseServerInfo baseServerInfo) {
                                             if(getView() != null) {
                                                 closeProgressDialog();
                                                 if(HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                                                     mDataBinding.commonFragmentList.stopRefresh();
                                                     mDataBinding.commonFragmentList.stopLoadMore();
                                                     return;
                                                 }
                                                 doSuccessResponse(refresh, response.body());
                                             }
                                         }
                                     }));
        }
        private void doSuccessResponse(boolean refresh, PbBean.PbResUserGetFollowList body) {
            if(body != null) {
                if(refresh) {
                    mAdapter.setData(UserSimpleItem.convert(body.getUserListList()));
                } else {
                    mAdapter.append(UserSimpleItem.convert(body.getUserListList()));
                }
                if(body.getUserListList().size() == 0) {
                    mDataBinding.commonFragmentList.setEmptyView(mDataBinding.tvEmptyData);
                }
                mDataBinding.commonFragmentList.setPullLoadEnable(body.getUserListList().size() == getPageLength());
                mDataBinding.commonFragmentList.stopRefresh();
                mDataBinding.commonFragmentList.stopLoadMore();
            }
        }
        private UserSimpleAdapter.OnUserFollowTypeListener createUserFollowTypeListener() {
            return new UserSimpleAdapter.OnUserFollowTypeListener() {
                @Override
                public void onAddFollow(String userId) {
                    addFollow(userId);
                }

                @Override
                public void onCancelFollow(String userId) {
                    cancelFollow(userId);
                }
            };
        }
        private void addFollow(final String userId) {
//            showProgressDialog();
            onNewRequestCall(UserAddFollowAction.newInstance(getContext(), userId).request(new AHttpService.IResCallback<PbBean.PbResUserAddFollow>() {
                @Override
                public void onCallback(int resultCode, Response<PbBean.PbResUserAddFollow> response, PbBean.PbBaseServerInfo baseServerInfo) {
                    if(getView() != null) {
//                        closeProgressDialog();
                        if(HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                            return;
                        }
                        refreshUserInfo(userId, true);

                        FollowEvent event = new FollowEvent();
                        event.setUserId(userId);
                        event.setIsAdd(true);
                        AppBus.getInstance().post(event);

                        ConfigUtils.addFollowCount(getActivity());
                    }
                }
            }));
        }
        private void refreshUserInfo(String userId, boolean isAddFollow) {
//            if (TextUtils.isEmpty(getArguments().getString("uid", ""))) {
                for (int i = 0; i < mAdapter.getCount(); i++) {
                    UserSimpleItem item = mAdapter.getItem(i);
                    if (TextUtils.equals(userId, item.userSimple.getUserId())) {
                        if (isAddFollow) {
                            item.type = (item.type == PbBean.PbSignUserFollowType.USER_FOLLOW_TYPE_FANS) ? PbBean.PbSignUserFollowType.USER_FOLLOW_TYPE_BOTH : PbBean.PbSignUserFollowType.USER_FOLLOW_TYPE_FOLLOW;
                        } else {
                            item.type = (item.type == PbBean.PbSignUserFollowType.USER_FOLLOW_TYPE_BOTH) ? PbBean.PbSignUserFollowType.USER_FOLLOW_TYPE_FANS : PbBean.PbSignUserFollowType.USER_FOLLOW_TYPE_NONE;
                        }
                    }
                }
                mAdapter.notifyDataSetChanged();
//            }
            ToastUtils.show(getContext(), isAddFollow ? "关注成功" : "取消了关注");

            EventBusUtil.post(new MessageNoticeEvent(MessageNoticeEvent.REFRESH_USER_INFO));
        }
        private void cancelFollow(final String userId) {
//            showProgressDialog();
            onNewRequestCall(UserCancelFollowAction.newInstance(getContext(), userId).request(new AHttpService.IResCallback<PbBean.PbResUserDelFollow>() {
                @Override
                public void onCallback(int resultCode, Response<PbBean.PbResUserDelFollow> response, PbBean.PbBaseServerInfo baseServerInfo) {
                    if (getView() != null) {
//                        closeProgressDialog();
                        if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                            return;
                        }
                        refreshUserInfo(userId, false);

                        FollowEvent event = new FollowEvent();
                        event.setUserId(userId);
                        event.setIsAdd(false);
                        AppBus.getInstance().post(event);

                        ConfigUtils.reduceFollowCount(getActivity());
                    }
                }
            }));
        }
    }
}
